package com.orm.tools.h3;

import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

public class Session {
	String tableName = "_student";
	Map<String, String> cfs = new HashMap<String, String>();
	String[] methodNames;

	public Session() {
		cfs.put("_id", "id");
		cfs.put("_name", "name");
		cfs.put("_age", "age");
		methodNames = new String[cfs.size()];
	}

	public void save(Student s) {

		String sql = createSQL();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			java.sql.Connection conn = DriverManager.getConnection(
					"jdbc:mysql://127.0.0.1/hibernate", "root", "root");
			java.sql.PreparedStatement ps = conn.prepareStatement(sql);
			//
			/*
			 * for(int i=0;i<cfs.size();i++) { ps.set }
			 */
			for (int i = 0; i < methodNames.length; i++) {
				Method method = s.getClass().getMethod(methodNames[i]);
				Class r = method.getReturnType();
				if (r.getName().equals("java.lang.String")) {
					String returnVal = (String) method.invoke(s);
					ps.setString(i + 1, returnVal);
				}
				if (r.getName().equals("int")) {
					Integer returnVal = (Integer) method.invoke(s);
					ps.setInt(i + 1, returnVal);
				}
				System.out.println(method.getName() + "|" + r.getName());
			}
			ps.executeUpdate();
			ps.close();
			conn.close();

		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	public String createSQL() {
		String str1 = "";
		int index = 0;
		for (String s : cfs.keySet()) {
			String v = cfs.get(s);
			v = Character.toUpperCase(v.charAt(0)) + v.substring(1);
			methodNames[index] = "get" + v;
			str1 += s + ",";
			index++;
		}
		str1 = str1.substring(0, str1.length() - 1);
		String str2 = "";
		for (int i = 0; i < cfs.size(); i++) {
			str2 += "?,";
		}
		str2 = str2.substring(0, str2.length() - 1);
		String sql = "insert into " + tableName + " ( " + str1 + " )"
				+ " values (" + str2 + ")";
		System.out.println(sql);
		return sql;
	}

}
